<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 6/3/21
 * Time: 3:25 PM
 */

namespace app\api\controller\v1;


use app\api\controller\BaseController;
use app\api\model\ProductOrder;
use app\api\model\StoreUser as StoreUserModel;
use app\api\model\Team;
use app\api\model\TeamUser as TeamUserModel;
use app\api\model\Store;
use app\api\model\User as UserModel;
use app\api\model\UserInvitation;
use app\api\model\UserMoney as UserMoneyModel;
use app\api\service\Token as TokenService;
use app\api\validate\CheckTeamUser;
use app\lib\exception\ParameterException;

class TeamUser extends BaseController
{
    // 验证当前用户信息绑定员工
    public function checkTeamUser($scene)
    {
        $scene = explode("-",$scene);
        if($scene[0] != 'team') {
            throw new ParameterException([
                'msg' => [
                    'store' => '二维码信息错误!'
                ]
            ]);
        }
        $uid = TokenService::getCurrentUid();
        $userInfo = UserModel::get($uid);
        if($userInfo['type'] != 1){
            throw new ParameterException([
                'msg' => [
                    'store' => '您已经绑定其他用户类型!'
                ]
            ]);
        }
        $storeInfo = Team::get($scene[1]);
        if(!$storeInfo) {
            throw new ParameterException([
                'msg' => [
                    'store' => '该团信息不存在!'
                ]
            ]);
        }
        return [ 'team_id' => $scene[1] ];
    }

    // 创建员工信息
    public function createData($team_id,$name,$phone,$desc)
    {
        (new CheckTeamUser())->goCheck();
        $uid = TokenService::getCurrentUid();
        $userInfo = UserModel::get($uid);
        if($userInfo['type'] != 1){
            throw new ParameterException([
                'msg' => [
                    'store' => '您已经绑定其他用户类型!'
                ]
            ]);
        }
        $teamInfo = Team::get($team_id);
        if(!$teamInfo) {
            throw new ParameterException([
                'msg' => [
                    'store' => '该店面信息不存在!'
                ]
            ]);
        }
        $mode = TeamUserModel::create([
            'name' => $name,
            'phone' => $phone,
            'desc' => $desc,
            'team_id' => $team_id,
            'user_id' => $uid
        ]);
        UserModel::where('id',$uid)->update([
            'type' => 6,
            'team_id' => $team_id
        ]);
        $data['scene'] = 'teamUser-'.$mode->id;
        $data['width'] = 280;
        $name = 'team_user_'.$mode->id;
        $token = new TokenService();
        $token->setCodePub($data,$name);
        return writeJson(202, [], '绑定成功！');
    }


    /**
     * 获取二维码
     */
    public function getCodeInfo()
    {
        $uid = TokenService::getCurrentUid();
        $store_user = TeamUserModel::where('user_id',$uid)->find();
        return [
            'team_url' => config('setting.invite_img_prefix').'/team_user_'.$store_user['id'].'.png',
        ];
    }


    /**
     * 获取销售额+收入
     */
    public function getStaffList()
    {
        $uid = TokenService::getCurrentUid();
        $teamUser = TeamUserModel::where('user_id',$uid)->find();
        $team = Team::where('id',$teamUser['team_id'])->with('product')->find();
        if($teamUser['type'] == 1) {
            $teamUser = TeamUserModel::where('team_id',$teamUser['team_id'])->select()->toArray();
            $team_user_ids = array_column($teamUser,'id');
            $user_ids = array_column($teamUser,'user_id');
            $userInvitation = UserInvitation::where('type','eq',3)
                ->where('inviter','in',$team_user_ids)
                ->select()->toArray();
            $ids = array_column($userInvitation,'invitee');
            $price = ProductOrder::where('user_id','in',$ids)
                ->where('status','gt',1)
                ->sum('actual_price');
            $price_one = ProductOrder::where('user_id','in',$user_ids)
                ->where('status','gt',1)
                ->sum('actual_price');
            $invite_money = UserMoneyModel::where('user_id',$uid)
                ->where('type',1)->sum('money');
            $order_count = ProductOrder::where('user_id','in',$ids)
                ->where('status','gt',1)
                ->count();
            $order_count_one = ProductOrder::where('user_id','eq',$uid)
                ->where('status','gt',1)
                ->count();
            return [
                'price' => $price + $price_one,
                'team' => $team,
                'invite_money' => $invite_money,
                'order_count' => $order_count,
                'order_count_one' =>  $order_count_one,
                'price_one' => $price_one,
            ];
        }elseif($teamUser['type'] == 2){
            $userInvitation = UserInvitation::where('type',3)
                ->where('inviter',$teamUser['id'])
                ->with('user')
                ->select()->toArray();

            $ids = array_column($userInvitation,'invitee');
            $price = ProductOrder::where('user_id','in',$ids)
                ->where('status','gt',1)
                ->sum('actual_price');
            $price_one = ProductOrder::where('user_id','eq',$uid)
                ->where('status','gt',1)
                ->sum('actual_price');
            $price = $price + $price_one;
            $invite_money = UserMoneyModel::where('user_id',$uid)
                ->where('type',1)->sum('money');
            $order_count = ProductOrder::where('user_id','in',$ids)
                ->where('status','gt',1)
                ->count();
            return [
                'price' => $price,
                'team' => $team,
                'invite_money' => $invite_money,
                'order_count' => $order_count,
                'order_count_one' => 0,
                'price_one' => 0,
            ];
        }
    }


    /**
     * 销售额排行
     */
    public function getRankList($user_id)
    {
        $uid = TokenService::getCurrentUid();
        $teamUser = TeamUserModel::where('user_id',$uid)->with('user')->find();
        $store = Team::get($teamUser['team_id']);
        $array = [];
        if($teamUser['type'] == 1) {
            $teamUsers = TeamUserModel::where('team_id',$teamUser['team_id'])
                ->with('user')->select()->toArray();
            foreach ($teamUsers as $k=>$v){
                $userInvitation = UserInvitation::where('type','eq',3)
                    ->where('inviter','eq',$v['id'])
                    ->select()->toArray();
                $ids = array_column($userInvitation,'invitee');
                $price = ProductOrder::where('user_id','in',$ids)
                    ->where('status','gt',1)
                    ->sum('actual_price');
                $price_one = ProductOrder::where('user_id','eq',$teamUsers[$k]['user_id'])
                    ->where('status','gt',1)
                    ->sum('actual_price');
                if(!$user_id) {
                    $price = $price + $price_one;
                }
                $teamUsers[$k]['price'] = $price;
                if($price > 0){
                    array_push($array,$teamUsers[$k]);
                }
            }
        } elseif($teamUser['type'] == 2){
            $store = $teamUser;
            $userInvitation = UserInvitation::where('type','eq',3)
                ->where('inviter','eq',$teamUser['id'])
                ->with('user')
                ->select()->toArray();
            foreach ($userInvitation as $k=>$v){
                $price = ProductOrder::where('user_id','eq',$v['invitee'])
                    ->where('status','gt',1)
                    ->sum('actual_price');
                $userInvitation[$k]['price'] = $price;
                if($price > 0){
                    array_push($array,$userInvitation[$k]);
                }
            }
            $teamUser['price'] = ProductOrder::where('user_id','eq',$teamUser['user_id'])
                ->where('status','gt',1)
                ->with('user')
                ->sum('actual_price');
            if($teamUser['price'] > 0){
                array_push($array,$teamUser->toArray());
            }
        }

        if(count($array) > 0) {
            $array = $this->arraySort($array,'price');
        }
        $store['rank'] = $array;
        return $store;
    }

    /**
     * 收入排行
     */
    public function getInviteRankList()
    {
        $uid = TokenService::getCurrentUid();
        $teamUser = TeamUserModel::where('user_id',$uid)->find();
        $invite_money = UserMoneyModel::where('user_id',$teamUser['user_id'])
                ->where('type',1)
                ->with('order')
                ->select()->toArray();
        return $invite_money;
    }

    /**
     * 裂变用户列表
     * 1. 查询每个店面的店员信息
     * 2. 查询每个店员所有的下级人员
     * 3. 判断下级用户是否登录手机号
     */
    public function getUserRankList()
    {
        $uid = TokenService::getCurrentUid();
        $teamUser = TeamUserModel::where('user_id',$uid)->find();
        $team = Team::get($teamUser['team_id']);
        $array = [];
        $teamUsers = TeamUserModel::where('team_id',$teamUser['team_id'])->with('user')->select()->toArray();
        foreach ($teamUsers as $k=>$v){
            $userInvitation = UserInvitation::where('type','eq',2)
                ->where('inviter','eq',$v['id'])
                ->select()->toArray();
            $ids = array_column($userInvitation,'invitee');
            $number = UserModel::where('id','in',$ids)->where('status','eq',3)->count();
            $teamUsers[$k]['number'] = $number;
            if($number > 0){
                array_push($array,$teamUsers[$k]);
            }
        }
        if(count($array) > 0) {
            $array = $this->arraySort($array,'number');
        }
        $team['rank'] = $array;
        return $team;
    }

    /**
     * 二维数组根据某个字段排序
     * @param array $array 要排序的数组
     * @param string $keys   要排序的键字段
     * @param string $sort  排序类型  SORT_ASC     SORT_DESC
     * @return array 排序后的数组
     */
    public function arraySort($array, $keys, $sort = SORT_DESC) {
        $keysValue = [];
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        array_multisort($keysValue, $sort, $array);
        return $array;
    }
}